/*******************************************************************************
 * Copyright 2010 DemandSpot
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.demandspot.client.table;

import java.util.Comparator;

import com.demandspot.client.Images;
import com.demandspot.client.Styles;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;

public class HeaderCell<X> extends Composite {

	private final HorizontalPanel body = new HorizontalPanel();
	private HTML title;
	private Image sortMarker;
	private String label;
	private int column;
	private Comparator<X> comparator;
	private Comparator<X> reverseComparator;
	
	public HeaderCell(int column, String label) {
		this(column, label, new DefaultTableComparator());
	}

	public HeaderCell(int column, String label, final Comparator<X> comparator) {
		initWidget(body);
		this.label = label;
		this.column = column;
		this.comparator = comparator;
		this.reverseComparator = new Comparator<X>() {
			public int compare(X o1, X o2) {
				return comparator.compare(o2, o1);
			}			
		};
		setStyleName(Styles.Util.getStyles().ds().tableHeader());
		createSortMarker(new Image(Images.Util.getImages().tableSortEmpty()));
		paint();
	}
	
	private final void paint() {		
		body.clear();
		title = new HTML(label);
		body.add(title);
		body.add(sortMarker);
	}
	
	public void update(SortState sortState) {
		body.remove(sortMarker);		
		if (sortState.getSortColumn() == column) {
			if (sortState.isAsc()) {						
				createSortMarker(new Image(Images.Util.getImages().tableSortAsc()));
			}
			else {
				createSortMarker(new Image(Images.Util.getImages().tableSortDesc()));
			}
			
		}			
		else {
			createSortMarker(new Image(Images.Util.getImages().tableSortEmpty()));
		}
		body.add(sortMarker);
	}
	
	private void createSortMarker(Image image) {
		this.sortMarker = image;
	}
	
	public Comparator<X> getComparator(SortState state) {
		if (state.isAsc()) {
			return comparator;
		}
		else {
			return reverseComparator;
		}
	}
	
}
